
import React, { useState, useEffect, useRef } from 'react'
import { Modal, Form, Tabs, Input, Button, Checkbox, Select, Row, Col, message, Spin } from 'antd';
import { setStore, getStore } from '@/utils/commons'
import VerifyBox from '@/components/verifyBox'
import Funs from '@/utils/Funs'
import API from '@/api/api'
import './index.scss';
const { TabPane } = Tabs;
const { Option } = Select;

function ChangePayPwd(props) {
    const [load, setLoad] = useState(false)
    const [phoneTimer, setPhoneTimer] = useState(0)
    const [emailTimer, setEmailTimer] = useState(0)
    const [form] = Form.useForm();
    const verifyPhoneRef = useRef();
    const verifyEmailRef = useRef();

    useEffect(() => {
        let interval;
        if (phoneTimer > 0) {
            interval = setInterval(() => {
                setPhoneTimer(phoneTimer - 1);
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [phoneTimer]);

    useEffect(() => {
        let interval;
        if (emailTimer > 0) {
            interval = setInterval(() => {
                setEmailTimer(emailTimer - 1);
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [emailTimer]);

    const sendPhoneCaptcha = async (captcha, key) => {
        let phoneArea = JSON.parse(getStore('userInfo')).phone_area
        let opts = { action: 'change_payment_password', type: 'phone', phoneArea: phoneArea, captcha: captcha, captchaKey: key };

        if (phoneTimer === 0) {
            setLoad(true)
            let sendCaptchaRes = await API.sendVerify(opts);
            if (sendCaptchaRes) {
                setPhoneTimer(60)
                setLoad(false)
                message.success("已成功发送验证码");
                cancelPhoneVerifyModal()
            } else {
                setLoad(false)
            }
        } else {
            message.warning("验证码发送间隔太短，请稍后再试")
        }
    }

    const sendEmailCaptcha = async (captcha, key) => {
        let opts = { action: 'change_payment_password', type: 'email', captcha: captcha, captchaKey: key };

        if (emailTimer === 0) {
            setLoad(true)
            let sendCaptchaRes = await API.sendVerify(opts);
            if (sendCaptchaRes) {
                setEmailTimer(60)
                setLoad(false)
                message.success("已成功发送验证码");
                cancelEmailVerifyModal()
            } else {
                setLoad(false)
            }
        } else {
            message.warning("验证码发送间隔太短，请稍后再试")
        }
    }

    const cancelModal = () => {
        props.close()
    }


    const cancelPhoneVerifyModal = () => {
        verifyPhoneRef.current.cancelModal()
    }

    const openPhoneVerifyModal = () => {
        verifyPhoneRef.current.openModal()
    }

    const cancelEmailVerifyModal = () => {
        verifyEmailRef.current.cancelModal()
    }

    const openEmailVerifyModal = () => {
        verifyEmailRef.current.openModal()
    }

    const onFinish = async (values) => {
        let opts = { password: values.password }
        if (values.phoneCaptcha) { opts.phoneCaptcha = values.phoneCaptcha }
        if (values.emailCaptcha) { opts.emailCaptcha = values.emailCaptcha }
        let res = await API.changePayPassword(opts)
        setLoad(true)
        if (res) {
            setLoad(false)
            message.success('修改支付密码成功')
            setTimeout(() => { window.location.reload() }, 500)
        } else {
            setLoad(false)
        }
    };

    const buttonPhoneAfter = (
        <a className="captcha-btn" onClick={openPhoneVerifyModal}> {phoneTimer === 0 ? '发送验证码' : phoneTimer + '秒'}</a>
    )

    const buttonEmailAfter = (
        <a className="captcha-btn" onClick={openEmailVerifyModal}> {emailTimer === 0 ? '发送验证码' : emailTimer + '秒'}</a>
    )

    return (
        <Modal className="change-paypassword" visible={props.status} onCancel={cancelModal} footer={null}>
            {
                !load ? null :
                    <div className="load-mark">
                        <Spin />
                    </div>
            }

            <Form
                form={form}
                className="bind-form"
                onFinish={onFinish}
            >
                <Row justify="center">
                    <h2 className="bind-title">修改支付密码</h2>
                </Row>
                {
                    !props.safeStatus.phone ? null :
                        <Form.Item name="phoneCaptcha" rules={[
                            { required: true, message: '输入验证码' }
                        ]}>
                            <Input className="bind-input" placeholder="输入手机验证码" suffix={buttonPhoneAfter} bordered={false} />
                        </Form.Item >
                }

                {
                    !props.safeStatus.email ? null :
                        <Form.Item name="emailCaptcha" rules={[
                            { required: true, message: '输入验证码' }
                        ]}>
                            <Input className="bind-input" placeholder="输入邮箱验证码" suffix={buttonEmailAfter} bordered={false} />
                        </Form.Item >
                }
                <Form.Item name="password" rules={[
                    { required: true, message: '请输入新密码', },
                    { pattern: new RegExp(/^\w{6,}$/), message: "支付密码不能低于6位" }
                ]}>
                    <Input.Password className="bind-input" placeholder="请输入新密码" bordered={false} />
                </Form.Item>
                <Form.Item name="passwordRetype" rules={[
                    { required: true, message: '请再次输入密码' },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                    }),
                ]}>
                    <Input.Password className="bind-input" placeholder="再输入密码" bordered={false} />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="bind-form-button">
                        修改
                    </Button>
                </Form.Item>
            </Form>
            <VerifyBox ref={verifyPhoneRef} send={sendPhoneCaptcha} />
            <VerifyBox ref={verifyEmailRef} send={sendEmailCaptcha} />
        </Modal>
    )
}

export default ChangePayPwd